package com.ews.onlineexchange.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Pattern;

import javax.imageio.stream.FileImageOutputStream;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ews.onlineexchange.util.AttachmentUtils;
import com.ews.onlineexchange.util.Config;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

public class CKEditorUploadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
    private static final String ERROR_FILE_UPLOAD = "An error occurred to the file upload process.";
    private static final String ERROR_NO_FILE_UPLOAD = "No file is present for upload process.";
    private static final String ERROR_INVALID_CALLBACK = "Invalid callback.";
    private static final String CKEDITOR_CONTENT_TYPE = "text/html; charset=UTF-8";
    private static final String CKEDITOR_HEADER_NAME = "Cache-Control";
    private static final String CKEDITOR_HEADER_VALUE = "no-cache";
    private static final Pattern PATTERN = Pattern.compile("[\\w\\d]*");
    private String errorMessage = "";
 	 @Override
 	 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  	 	doPost(request, response);
 	 }
	 @Override
	 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 	final PrintWriter out = response.getWriter();
	        response.setContentType(CKEDITOR_CONTENT_TYPE);
	        response.setHeader(CKEDITOR_HEADER_NAME, CKEDITOR_HEADER_VALUE);
		 // CKEditorFuncNum Is the location to display when the callback
	        FileItemFactory factory = new DiskFileItemFactory();
	        ServletFileUpload upload = new   ServletFileUpload(factory);
	        String ckeditorImagesPath = Config.getPropertyIncludePrefix("saveDir");
	        final String pathToFile =	Config.getPropertyIncludePrefix("uploadContextPath") + "/";
	        errorMessage = "";
	        File dir = new File(ckeditorImagesPath);
	        String fileName = "";
	        try {
	        	   List<DiskFileItem> items = upload.parseRequest(request);
	        	   if (!items.isEmpty() && items.get(0) != null) {
	        		  if(!dir.exists()) {
	        			  dir.mkdirs();
	        		  }
	        		  DiskFileItem item = items.get(0);
	        		   fileName = item.getName();
	        		  String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);  
	        		  fileName = System.currentTimeMillis()+"."+suffix;
	        		  byte [] byteArr = item.get();
	        		  FileImageOutputStream imageOutput = new FileImageOutputStream(new File(ckeditorImagesPath+fileName));//打开输入流
	        		    imageOutput.write(byteArr, 0, byteArr.length);//将byte写入硬盘
	        		    imageOutput.close();
	        	   } else {
	        	    errorMessage = ERROR_NO_FILE_UPLOAD;
	        	   }
	        	 
	        	  } catch (FileUploadException e) {
	        	   errorMessage = ERROR_FILE_UPLOAD;
	        	 }
	        String callback = request.getParameter("CKEditorFuncNum");
	        if (!PATTERN.matcher(callback).matches()) {
	            callback = "";
	            errorMessage = ERROR_INVALID_CALLBACK;
	        }
	       
	        out.println("<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction("
	                + callback + ",'" + (pathToFile + fileName) + "','" + errorMessage + "')");
	        out.println("</script>");
	        out.flush();
	        out.close();
	}

	 
}
